// static/js/schedule_free.js
;(function(){
  document.addEventListener('DOMContentLoaded', () => {
    const openFree = document.getElementById('open-free-modal');
    const freeModal = new bootstrap.Modal(document.getElementById('freeModal'));
    const startIn = document.getElementById('free-start-date');
    const endIn   = document.getElementById('free-end-date');
    const searchBtn = document.getElementById('free-search');
    const tbody     = document.getElementById('free-body');

    // 打开 Modal 时初始化
    openFree.addEventListener('click', e => {
      e.preventDefault();
      const today = new Date().toISOString().slice(0,10);
      startIn.value = today;
      endIn.value   = today;
      tbody.innerHTML = '';
      freeModal.show();
    });

    // 查询空闲课时
    searchBtn.addEventListener('click', async () => {
      if (!startIn.value || !endIn.value) {
        startIn.reportValidity();
        return;
      }
      const params = new URLSearchParams({
        start_date: startIn.value,
        end_date:   endIn.value
      });
      const res = await fetch('/api/schedules/free?' + params);
      const list = res.ok ? await res.json() : [];
      // 渲染
      tbody.innerHTML = '';
      list.forEach(item => {
        const tr = document.createElement('tr');
        const frees = item.free.join(item.free[0]==='当日无排课'? '': '<br>');
        tr.innerHTML = `
          <td>${item.date}</td>
          <td>${frees}</td>
        `;
        tbody.appendChild(tr);
      });
    });
  });
})();
